package dao;

import model.Student;
import org.hibernate.Session;
import util.HibernateUtil;

import java.util.ArrayList;
import java.util.List;



public class StudentDaoImpl implements StudentDao{

    Session session;

    public void createStudent(Student student) {
       try{
       session = HibernateUtil.getSession().openSession();
       session.beginTransaction();
       session.save(student);
       session.getTransaction().commit();
    } catch (Exception e) {
           e.printStackTrace();
       }
      finally {
       if (session.isOpen()|| session != null){
           session = null;
       }
       }
    }

    public Student readStudent(int id) {
      Student student = null;
        try{
            session = HibernateUtil.getSession().openSession();
            student = (Student) session.load(Student.class,id);

        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (session.isOpen()|| session != null){
                session = null;
            }
        }
       return student;
    }


    public void updateStudent(Student student) {
        try{
            session = HibernateUtil.getSession().openSession();
            session.beginTransaction();
            session.update(student);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (session.isOpen()|| session != null){
                session = null;
            }
        }
    }


    public void deleteStudent(Student student) {

            try{
                session = HibernateUtil.getSession().openSession();
                session.beginTransaction();
                session.delete(student);
                session.getTransaction().commit();
            } catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                if (session.isOpen()|| session != null){
                    session = null;
                }
            }
    }


    public List<Student> getAllStudents() {
        Session session = null;
        List<Student> studs = new ArrayList<Student>();
        try {
            session = HibernateUtil.getSession().openSession();
            studs = session.createCriteria(Student.class).list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return studs;
    }
}
